<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'
import { add, delById, delByIds, getById, page, update } from '@/api/dict_item'

const props = defineProps({
  id: { // 这是dictHeaderId
    type: Number,
    default: 0,
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
})
const emit = defineEmits(['update:modelValue'])
const formRef = ref<FormInstance>()

const myVisible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})

const title = '字典值'
const myDialogVisible = ref(false)
function onSubmit() {
  onCancel()
}

function onCancel() {
  myVisible.value = false
}

/// ///////////////////////////////////////////////////////page////////////////////////
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } = usePagination()

const tableRef = ref()
const loadingDialog = ref(false)
const form = ref({
  id: 0,
  header_id: props.id,
  label: '',
  value: '',
  status: '',
  sort: 999,
  desc: '',
})
const formRules = ref<FormRules>({
  label: [
    { required: true, message: '请输入标签', trigger: 'blur' },
  ],
  value: [
    { required: true, message: '请输入编号', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请输入状态', trigger: 'blur' },
  ],
})
const data = ref({
  loading: false,
  // 详情
  formDrawerProps: {
    visible: false,
    id: 0,
  },
  // 搜索
  search: {
    headerId: 0,
    label: '',
    value: '',
    status: '',
  },
  // 批量操作
  batch: {
    enable: true,
    selectionDataList: [],
  },
  // 列表数据
  dataList: [],
})
const titleDialog = computed(() => form.value.id === 0 ? '新增' : '编辑')
function onDialogSubmit() {
  if (form.value.id === 0) {
    formRef.value && formRef.value.validate((valid) => {
      if (valid) {
        form.value.sort = Number.parseInt(`${form.value.sort}`)
        add(form.value).then((res: any) => {
          if (res.code !== 200) {
            ElMessage.error({
              message: res.msg,
              center: true,
            })
          }
          else {
            ElMessage.success({
              message: '新增条目成功',
              center: true,
            })
            getDataPage()
          }
          onDialogCancel()
        })
      }
    })
  }
  else {
    formRef.value && formRef.value.validate((valid) => {
      if (valid) {
        form.value.sort = Number.parseInt(`${form.value.sort}`)
        update(form.value).then((res: any) => {
          if (res.code !== 200) {
            ElMessage.error({
              message: res.msg,
              center: true,
            })
          }
          else {
            ElMessage.success({
              message: '编辑条目成功',
              center: true,
            })
            getDataPage()
          }
          onDialogCancel()
        })
      }
    })
  }
}

function onDialogCancel() {
  myDialogVisible.value = false
}
onMounted(() => {
  if (form.value.header_id !== 0) {
    data.value.search.headerId = form.value.header_id
    getDataPage()
  }
})
function getDataPage() {
  data.value.loading = true
  const params = getParams() as any
  data.value.search.headerId && (params.headerId = data.value.search.headerId)
  data.value.search.label && (params.label = data.value.search.label)
  data.value.search.value && (params.value = data.value.search.value)
  data.value.search.status && (params.status = data.value.search.status)
  page(params).then((res) => {
    data.value.loading = false
    data.value.dataList = res.data.list
    pagination.value.total = res.data.total
  })
}

// 每页数量切换
function sizeChange(size: number) {
  onSizeChange(size).then(() => getDataPage())
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataPage())
}

// 字段排序
function sortChange({ prop, order }: { prop: string, order: string }) {
  onSortChange(prop, order).then(() => getDataPage())
}

function onCreate() {
  form.value.id = 0
  form.value.label = ''
  form.value.value = ''
  form.value.status = ''
  form.value.desc = ''
  myDialogVisible.value = true
}

function onEdit(row: any) {
  getById(row.id).then((res: any) => {
    if (res.code !== 200) {
      ElMessage.error({
        message: res.msg,
        center: true,
      })
    }
    else {
      form.value = res.data
    }
  })
  myDialogVisible.value = true
}

function onDel(row: any) {
  ElMessageBox.confirm(`确认删除「${row.real_name}」吗？`, '确认信息').then(() => {
    delById(row.id).then((res: any) => {
      if (res.code !== 200) {
        ElMessage.error({
          message: res.msg,
          center: true,
        })
      }
      else {
        getDataPage()
        ElMessage.success({
          message: '删除成功',
          center: true,
        })
      }
    })
  }).catch(() => { })
}
function onBatchDel() {
  ElMessageBox.confirm('确认批量删除？', '确认信息').then(() => {
    const ids = data.value.batch.selectionDataList.map((item: any) => item.id)
    delByIds(ids).then((res: any) => {
      if (res.code !== 200) {
        ElMessage.error({
          message: res.msg,
          center: true,
        })
      }
      else {
        getDataPage()
        ElMessage.success({
          message: '删除成功',
          center: true,
        })
      }
    })
  }).catch(() => { })
}
/// ///////////////////////////////////////////////////////page////////////////////////
</script>

<template>
  <div>
    <el-drawer v-model="myVisible" :title="title" size="800px" :close-on-click-modal="true" destroy-on-close>
      <div>
        <page-main>
          <search-bar>
            <el-form :model="data.search" size="default" label-width="100px" label-suffix="：">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="名称">
                    <el-input
                      v-model="data.search.label" placeholder="请输入名称" clearable
                      @keydown.enter="currentChange()" @clear="currentChange()"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="标识">
                    <el-input
                      v-model="data.search.value" placeholder="请输入标识" clearable
                      @keydown.enter="currentChange()" @clear="currentChange()"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="状态">
                    <el-radio-group v-model="data.search.status" size="default" @change="currentChange()">
                      <el-radio label="">
                        全部
                      </el-radio>
                      <el-radio label="0">
                        使能
                      </el-radio>
                      <el-radio label="1">
                        关闭
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </search-bar>
          <div class="btn-op-container">
            <batch-action-bar
              v-if="data.batch.enable" :data="data.dataList" :selection-data="data.batch.selectionDataList"
              @check-all="tableRef.toggleAllSelection()" @check-null="tableRef.clearSelection()"
            >
              <el-button size="default" type="danger" @click="onBatchDel">
                批量删除
              </el-button>
            </batch-action-bar>
            <el-button style="margin-left: 10px;" type="primary" size="default" @click="onCreate">
              <template #icon>
                <el-icon>
                  <svg-icon name="i-ep:plus" />
                </el-icon>
              </template>
              新增
            </el-button>
            <el-button type="primary" @click="currentChange()">
              <template #icon>
                <el-icon>
                  <svg-icon name="i-ep:search" />
                </el-icon>
              </template>
              搜索
            </el-button>
          </div>
          <el-table
            ref="tableRef" v-loading="data.loading" class="list-table" :data="data.dataList"
            stripe highlight-current-row border @sort-change="sortChange" @selection-change="data.batch.selectionDataList = $event"
          >
            <el-table-column v-if="data.batch.enable" type="selection" align="center" fixed />
            <el-table-column prop="label" label="名称" />
            <el-table-column prop="value" label="标识" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag v-if="scope.row.status === '0'" type="success" size="small">
                  使能
                </el-tag>
                <el-tag v-else type="danger" size="small">
                  关闭
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="desc" label="描述" />
            <el-table-column label="操作" width="250" align="center" fixed="right">
              <template #default="scope">
                <el-button type="danger" size="small" plain @click="onDel(scope.row)">
                  删除
                </el-button>
                <el-button type="primary" size="small" plain @click="onEdit(scope.row)">
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="pagination.page" :total="pagination.total" :page-size="pagination.size"
            :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false" class="pagination"
            background @size-change="sizeChange" @current-change="currentChange"
          />
        </page-main>
        <DrawerForm
          v-if="data.formDrawerProps.visible === true"
          :id="data.formDrawerProps.id"
          v-model="data.formDrawerProps.visible"
        />
      </div>
      <template #footer>
        <el-button size="large" @click="onCancel">
          取消
        </el-button>
        <el-button type="primary" size="large" @click="onSubmit">
          确定
        </el-button>
      </template>
    </el-drawer>
    <el-dialog
      v-model="myDialogVisible" :title="titleDialog" width="600px" :close-on-click-modal="false" append-to-body
      destroy-on-close
    >
      <div v-loading="loadingDialog">
        <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px" label-suffix="：">
          <el-form-item label="名称" prop="label">
            <el-input v-model="form.label" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="标识" prop="value">
            <el-input v-model="form.value" placeholder="请输入标识" />
          </el-form-item>
          <el-form-item label="使能" prop="status">
            <el-radio-group v-model="form.status" size="default">
              <el-radio label="0">
                使能
              </el-radio>
              <el-radio label="1">
                关闭
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="form.desc" :row="2" type="textarea" placeholder="备注说明" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="large" @click="onDialogCancel">
          取消
        </el-button>
        <el-button type="primary" size="large" @click="onDialogSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
}

.el-drawer__header {
  margin-bottom: 0;
}

.btn-op-container {
  display: flex;
}
</style>
